﻿/*
 * Author:czy@vip.163.com
 * 
Microsoft Public License (Ms-PL)

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions

The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.

A "contribution" is the original software, or any additions or changes to the software.

A "contributor" is any person that distributes its contribution under this license.

"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.

(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.

(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.

(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.

(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ObjectCache
{

    public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2);
    public delegate TResult Func<TResult>();
    public delegate void Action();

    public sealed class Cache<TKey, TItem> : ICacheJob, ICache<TKey, TItem> where TKey : IEquatable<TKey>
    {
        private const int ReaderLockTime = 120000;
        private const int WriteLockTime = 10000;
        class CacheItem
        {
            public TKey Key { get; set; }
            public TItem Item { get; set; }
            public BaseToken Token { get; set; }
        }

        private List<CacheItem> mItemList = new List<CacheItem>();

        private ReaderWriterLock mRWLock = new ReaderWriterLock();

        private Action mOnReset;
        public Action OnReset
        {
            get { return mOnReset; }
            set { mOnReset = value; }
        }

        internal Cache()
        {
        }

        public void Add(TKey key, TItem item, BaseToken token)
        {
            Add(new Cache<TKey, TItem>.CacheItem
            {
                Key = key,
                Item = item,
                Token = token
            });
        }

        private void Add(CacheItem cacheItem)
        {
            mRWLock.AcquireWriterLock(WriteLockTime);
            try
            {
                var item = mItemList.Find(n => n.Key.Equals(cacheItem.Key));
                if (item != null)
                {
                    mItemList.Remove(item);
                    cacheItem.Token.ResetFilter |= item.Token.ResetFilter;
                    mItemList.Add(cacheItem);
                }
                else
                    mItemList.Add(cacheItem);
            }
            finally
            {
                mRWLock.ReleaseWriterLock();
            }
        }

        public void AddIfNotExists(TKey key, Func<TItem> getvalues, BaseToken token)
        {
            mRWLock.AcquireWriterLock(WriteLockTime);
            try
            {
                var item = mItemList.Find(n => n.Key.Equals(key));
                if (item == null)
                {
                    mItemList.Add(new Cache<TKey, TItem>.CacheItem
                    {
                        Key = key,
                        Item = getvalues(),
                        Token = token
                    });
                }
            }
            finally
            {
                mRWLock.ReleaseWriterLock();
            }
        }

        public void AddRange(IEnumerable<KeyValuePair<TKey, TItem>> items, BaseToken token)
        {
            if (items == null)
                return;

            mRWLock.AcquireWriterLock(WriteLockTime);
            try
            {

                List<KeyValuePair<TKey, TItem>> newItemList = new List<KeyValuePair<TKey, TItem>>(items);

                foreach (var newItem in newItemList)
                {
                    var item = mItemList.Find(n => n.Key.Equals(newItem.Key));
                    if (item != null)
                    {
                        mItemList.Remove(item);
                        token.ResetFilter |= item.Token.ResetFilter;
                    }
                    mItemList.Add(new Cache<TKey, TItem>.CacheItem
                    {
                        Key = newItem.Key,
                        Item = newItem.Value,
                        Token = token
                    });
                }
            }
            finally
            {
                mRWLock.ReleaseWriterLock();
            }
        }

        public void AddRange(Func<IEnumerable<KeyValuePair<TKey, TItem>>> getRange, BaseToken token)
        {
            mRWLock.AcquireWriterLock(WriteLockTime);

            try
            {

                var items = getRange();
                if (items == null)
                    return;

                List<KeyValuePair<TKey, TItem>> newItemList = new List<KeyValuePair<TKey, TItem>>(items);

                foreach (var newItem in newItemList)
                {
                    var item = mItemList.Find(n => n.Key.Equals(newItem.Key));
                    if (item != null)
                    {
                        mItemList.Remove(item);
                        token.ResetFilter |= item.Token.ResetFilter;
                    }
                    mItemList.Add(new Cache<TKey, TItem>.CacheItem
                    {
                        Key = newItem.Key,
                        Item = newItem.Value,
                        Token = token
                    });
                }
            }
            finally
            {
                mRWLock.ReleaseWriterLock();
            }
        }
        public void Remove(TKey key)
        {
            mRWLock.AcquireReaderLock(ReaderLockTime);
            try
            {
                var item = mItemList.Find(n => n.Key.Equals(key));
                if (item != null)
                {
                    var wLock = mRWLock.UpgradeToWriterLock(WriteLockTime);
                    mItemList.Remove(item);
                    mRWLock.DowngradeFromWriterLock(ref wLock);
                }
            }
            finally
            {
                mRWLock.ReleaseReaderLock();
            }
        }

        public bool TryGet(TKey key, out TItem outItem)
        {
            mRWLock.AcquireReaderLock(ReaderLockTime);
            try
            {
                var item = mItemList.Find(n => n.Key.Equals(key));
                if (item == null)
                {
                    outItem = default(TItem);
                    return false;
                }
                else
                    outItem = item.Item;

                item.Token.Renew();
                return true;
            }
            finally
            {
                mRWLock.ReleaseReaderLock();
            }
        }

        public bool ContainsKey(TKey key)
        {
            TItem item;
            return TryGet(key, out item);
        }

        public TItem Get(TKey key)
        {
            TItem item;
            TryGet(key, out item);
            return item;
        }

        public TItem GetWithCreate(TKey key, Func<TItem> createItem, BaseToken token)
        {
            mRWLock.AcquireReaderLock(ReaderLockTime);
            try
            {
                var item = mItemList.Find(n => n.Key.Equals(key));
                if (item == null)
                {
                    var rLock = mRWLock.UpgradeToWriterLock(WriteLockTime);

                    try
                    {
                        item = mItemList.Find(n => n.Key.Equals(key));
                        if (item != null)
                            return item.Item;

                        item = new Cache<TKey, TItem>.CacheItem
                        {
                            Key = key,
                            Item = createItem(),
                            Token = token
                        };

                        Add(item);
                    }
                    finally
                    {
                        mRWLock.DowngradeFromWriterLock(ref rLock);
                    }
                }
                else
                    item.Token.Renew();

                return item.Item;
            }
            finally
            {
                mRWLock.ReleaseReaderLock();
            }
        }

        public long Count()
        {
            mRWLock.AcquireReaderLock(ReaderLockTime);
            try
            {
                return mItemList.Count;
            }
            finally
            {
                mRWLock.ReleaseReaderLock();
            }
        }

        public void BeginAddRange()
        {
            mRWLock.AcquireWriterLock(WriteLockTime);
        }

        public void EndAddRange()
        {
            mRWLock.ReleaseWriterLock();
        }

        #region ICacheJob Members

        public void Reset()
        {
            ((ICacheJob)this).Reset(0);
        }

        

        #endregion

        #region IDisposable Members

        #endregion


        void ICacheJob.Reset(long resetFilter)
        {
            mRWLock.AcquireWriterLock(WriteLockTime);
            try
            {
                if (resetFilter == 0)
                {
                    if (typeof(TItem) is IDisposable)
                    {
                        mItemList.ForEach(n => ((IDisposable)n).Dispose());
                    }
                    mItemList.Clear();
                }
                else
                {
                    var resetItems = mItemList.FindAll(n => (n.Token.ResetFilter & resetFilter) != 0);
                    if (typeof(TItem) is IDisposable)
                    {
                        resetItems.ForEach(n => ((IDisposable)n).Dispose());
                    }
                    resetItems.ForEach(n => mItemList.Remove(n));
                }

                if (mOnReset != null)
                    mOnReset();
            }
            finally
            {
                mRWLock.ReleaseWriterLock();
            }
        }


        #region ICacheJob Members


        void ICacheJob.CheckExpiration()
        {
            mRWLock.AcquireReaderLock(ReaderLockTime);
            try
            {
                for (int i = 0; i < mItemList.Count; i++)
                {
                    var current = mItemList[i];
                    if (!current.Token.IsCurrent)
                    {
                        var wLock = mRWLock.UpgradeToWriterLock(WriteLockTime);

                        try
                        {
                            if (!mItemList.Contains(current))
                                continue;
                            else
                            {
                                mItemList.RemoveAt(i);
                                i--;
                                continue;
                            }
                        }
                        finally
                        {
                            mRWLock.DowngradeFromWriterLock(ref wLock);
                        }
                    }
                }
            }
            finally
            {
                mRWLock.ReleaseReaderLock();
            }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            ((ICacheJob)this).Reset(0);
        }

        #endregion
    }

}
